//
//  MagicMoveInverseTransition.m
//  MagicMoveDemo
//
//  Created by 卢小辉 on 15/10/15.
//  Copyright © 2015年 lulee007. All rights reserved.
//

#import "MagicMoveInverseTransition.h"
#import "SecondViewController.h"
#import "FirstCollectionViewController.h"
#import "CollectionViewCell.h"

@implementation MagicMoveInverseTransition


- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext{
    return 0.6f;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
    
    
    //获得 from & to controller，获得container
    SecondViewController *fromVC=(SecondViewController*)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    FirstCollectionViewController *toVC=(FirstCollectionViewController*)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *container=[transitionContext containerView];
    
    //获得cell 以用来截图
    CollectionViewCell *cell=(CollectionViewCell *)[toVC.collectionView cellForItemAtIndexPath:toVC.indexPath];
    UIView *snapShot=[fromVC.imageViewForSecond snapshotViewAfterScreenUpdates:NO];
    snapShot.frame=[container convertRect:fromVC.imageViewForSecond.frame   fromView:fromVC.view];
    
    //隐藏实际位置的两个图
    cell.imageView.hidden=YES;
    fromVC.imageViewForSecond.hidden=YES;
    
    //提前设置tovc的frame
    toVC.view.frame=[transitionContext finalFrameForViewController:toVC];
    
    //添加 toView 和 snapshot到container
    [container insertSubview:toVC.view belowSubview:fromVC.view];
    [container addSubview:snapShot];
    
    //执行动画
    [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.0f usingSpringWithDamping:1.0f initialSpringVelocity:1.0f options:UIViewAnimationOptionCurveLinear animations:^{
        //设置动画末fromvc的状态===隐藏
        fromVC.view.alpha=0.0f;
        //设置动画末截图的frame与cell的位置匹配
        snapShot.frame=toVC.finalCellFrame;
        
    } completion:^(BOOL finished) {
        //动画结束，移除 截图
        [snapShot removeFromSuperview];
        //还原 cell image 与 fromvc image的状态到可见
        cell.imageView.hidden=NO;
        fromVC.imageViewForSecond.hidden=NO;
        //结束动画
        [transitionContext completeTransition:!transitionContext.transitionWasCancelled];
        
    }];
    
}

@end
